/**
 * 
 */
package com.bjSoft.regressionTestTool.core.codeCoverage.action;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import net.sf.saxon.trans.XPathException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;

import com.bjSoft.regressionTestTool.codeCoverage.CoverageMatrixMaker;
import com.bjSoft.regressionTestTool.codeCoverage.CoverageMatrixWriter;
import com.bjSoft.regressionTestTool.codeCoverage.base.ClassCoverageInfo;

/**
 * @author Breno
 *
 */
public class AuxiliarCoverageAction {
	
	public AuxiliarCoverageAction() {
		
	}
	
	public  void getCoverageData(IProject project) {
		try {
			project.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		IResource coverageDataFolder = 
			project.getFolder(new Path("/emmaInstr/coverageData"));
		if (coverageDataFolder != null && coverageDataFolder instanceof IFolder) {
			IFolder coverageFolder = (IFolder) coverageDataFolder;
			try {
				generateMatrix(coverageFolder.members(), project);
			} catch (CoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (XPathException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}			
	
	}

   private void generateMatrix(IResource[] members, IProject project) throws IOException, XPathException {
		File coverageResult = new File(project.getLocation().toOSString() 
				+ "\\emmaInstr\\coverageData\\projectCoverage.txt");
		if (!coverageResult.exists()) {
			coverageResult.delete();
		}
		if (coverageResult.createNewFile()) {
			CoverageMatrixMaker coverageMatrix =
				new CoverageMatrixMaker();
			for (int i = 0; i < members.length; i++) {
				if (members[i] instanceof IFile) {
					IFile covFile = (IFile) members[i];
					coverageMatrix.generateMatrixEntry(covFile.getLocation().toFile());
				}
			}
			HashMap<String, ClassCoverageInfo> coverageData = 
				coverageMatrix.getCoverageInfo();
			CoverageMatrixWriter.writeMatrix(coverageData, project.getLocation());
		}
	
   }
}
